﻿using DataAccess;
using DataAccess.DAL;
using DataAccess.DTO;
using DataAccess.Models;
using DataAccess.Solr;
using DataAccess.ViewModel.API;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using System.Data;
namespace Api.Controllers
{
    public class OrderController : ApiController
    {


        /// <summary>
        /// 添加订单统计
        /// </summary>
        /// <param name="content">订单集合json</param>
        /// <param name="mamaid">阿里妈妈ID</param>
        /// <param name="promoter_id">推广者ID</param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Effect")]
        public HttpResponseMessage Effect(List<EffectDTO> values, string excTime, string promoter_id, string mamaid)
        {

            if (values == null || values.Count < 0)
            {
                return ResultHand.OnResult(new Result { State = false, Message = "订单汇总数据不正确" });
            }
            string Log = "";
            if (!string.IsNullOrEmpty(excTime))
            {
                int Count =  ProductEffectDAL.Delte(string.Format(@"delete from ProductEffect_{0} where datediff(day,CreateDate,'{1}')=0", promoter_id, excTime));
                Log += "删除" + Count+"条";
            }

            List<AgencyUsers> AgencyUsersList = new AgencyUsersDAL().GetListBy_Promoter_Id(int.Parse(promoter_id));

            string TableName = string.Format("ProductEffect_{0}", promoter_id);
            DataTable dt = GetTableEffect();
            foreach (var item in values)
            {

                DataRow r = dt.NewRow();
                r["Id"] = 0;
                r["CreateDate"] = Convert.ToDateTime(item.CreateDate);
                r["PromotionBit"] = item.PromotionBit;
                r["ClickNum"] = item.ClickNum;
                r["PayNum"] = item.PayNum;
                r["Estimate"] = item.Estimate;
                r["Income"] = item.Income;
                //1：网站，2微信，3QQ
                r["PromotionType"] = item.PromotionType == "wz" ? "1" : (item.PromotionType == "wx" ? "2" : "3");
                r["LastDate"] = item.LastDate;
              //  r["promoter_id"] = item.promoter_id;
                string UserName = "";
                int Rate_i = 0;//一级分佣
                string UserName_i = "";//一级用户账号
                int Rate_ii = 0;//二级分佣
                string UserName_ii = "";//二级账号
                if (item.PromotionBit != "" && item.PromotionBit.Contains("_"))
                {
                    string[] userArray = item.PromotionBit.Split('_');
                    UserName = userArray[1];//当前用户账号
                    var user = AgencyUsersList.Find(c => c.username == UserName);
                    if (user == null)
                        user = new AgencyUsers();
                    r["Rate"] = user.commission;//当前用户自己比例
                    Rate_i = user.superior_commission;//上级分佣
                    Rate_ii = user.onthe_superior;//上上级分佣
                    //如果有下级代理
                    if (user.superior != 0)
                    {
                        //上级代理信息
                        var OntheUser = AgencyUsersList.Find(c => c.id == user.superior);
                        UserName_i = OntheUser.username;
                        //上级是否还有上级
                        if (user.onthe_superior != 0)
                        {
                            //上上级代理信息
                            var User3 = AgencyUsersList.Find(c => c.id == user.onthe_superior);
                            UserName_ii = User3.username;
                        }
                    }
                }
                r["UserName"] = UserName;
                r["Rate_i"] = Rate_i;
                r["UserName_i"] = UserName_i;
                r["Rate_ii"] = Rate_ii;
                r["UserName_ii"] = UserName_ii;

                r["AlimamaId"] = mamaid;

                dt.Rows.Add(r);
            }
          
            ProductEffectDAL.BulkToDB(dt, TableName);
            Log += "插入" + dt.Rows.Count;
            return ResultHand.OnResult(new Result { State = true, Message = "订单存储成功", Datas = Log });
        }

        /// <summary>
        /// 微信群管机器人搜索
        /// </summary>
        /// <param name="KeyWord">关键词</param>
        /// <param name="promoter_id">推广者ID</param>
        /// <param name="agentid">推广者下面代理ID</param>
        /// <param name="SearchUserName">搜索者的当前微信群昵称</param>
        /// <param name="Wxq_id">微信群名称</param>
        /// <returns>搜索的条数</returns>
        [HttpPost]
        [Route("api/Search")]
        public HttpResponseMessage Search(string KeyWord, string promoter_id, string agentid, string SearchUserName = "", string Wxq_id = "")
        {

            if (string.IsNullOrEmpty(KeyWord.Trim()))
            {
                return ResultHand.OnResult(new Result { State = false, Message = "关键词不正确" });
            }
            if (string.IsNullOrEmpty(promoter_id) || promoter_id == "0")
            {
                return ResultHand.OnResult(new Result { State = false, Message = "promoter_id不正确" });
            }
            if (string.IsNullOrEmpty(agentid) || agentid == "0")
            {
                return ResultHand.OnResult(new Result { State = false, Message = "agentid不正确" });
            }

            string strwhere = "(";
            strwhere += string.Format("(productname:{0})", KeyWord.Trim().Replace(" ", ""));
            strwhere += ")";
            string Order = "synchro_date desc";
            PagingList<ProductIndex> plist = new SolrIndexInfoBLL().GetProductList(strwhere, 0, 1, Order);
            DataAccess.DAL.SearchKeyWordDAL.InsertKeyWord(int.Parse(agentid), int.Parse(promoter_id), 2, KeyWord, SearchUserName, plist.Total, Wxq_id, XYD.Common.Request.GetIP(), "微信群内搜索");
            Result result = new Result();
            return ResultHand.OnResult(new Result { State = true, Message = "查询成功", Datas = plist.Total });
        }


        /// <summary>
        /// 新增当天订单数据和删除
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/tkorder")]
        public HttpResponseMessage tkorder(List<OrderDTO> values)
        {
            string Log = "";
            if (values != null && values.Count > 0)
            {
                //删除
                List<OrderDTO> list = values.FindAll(c => c.DateType ==1);
               
                if (list.Count > 0)
                {
                    string DelStr = "";
                    foreach (var item in list)
                    {
                        DelStr += string.Format("DELETE FROM Orders_{0} WHERE ProductID={1} AND OrderID='{2}' AND BatchNumber!='{3}'; ",item.promoter_id,item.ProductID,item.OrderID,item.BatchNumber);

                    }
                    if (DelStr != "")
                    {
                        OrdersDAL.BulkDelte(DelStr);
                    }
                    Log += "删除了：" + list.Count+"条....";
                }
                string TableName="";
                DataTable dt = GetTableSchema();
                foreach (var item in values)
                {
                    if (TableName == "")
                        TableName = string.Format("Orders_{0}", item.promoter_id);
  
                    DataRow r = dt.NewRow();
                    r["Id"] = 0;
                    r["CreateDate"] =Convert.ToDateTime(item.CreateDate);
                    r["ClickDate"] = Convert.ToDateTime(item.ClickDate);
                    r["ProductDes"] = item.ProductDes;
                    r["ProductID"] = item.ProductID;
                    r["ShopName"] = item.ShopName;
                    r["ProductNum"] = item.ProductNum;
                    r["ProductPrice"] = item.ProductPrice;
                    r["OrderStateDes"] = item.OrderStateDes;
                    r["OrderType"] = item.OrderType;
                    r["IncomeRatio"] = item.IncomeRatio;
                    r["DividedIntoRatio"] = item.DividedIntoRatio;
                    r["PayPrice"] = item.PayPrice;
                    r["EffectPrediction"] = item.EffectPrediction;
                    r["SettlementPrice"] = item.SettlementPrice;
                    r["EstimatedRevenue"] = item.EstimatedRevenue;
                    object obj = item.SettlementDate;
                    if (item.SettlementDate=="")
                    {
                        obj =DBNull.Value;
                    }
                    r["SettlementDate"] = obj;
                    r["CommissionRate"] = item.CommissionRate;
                    r["CommissionPrice"] = item.CommissionPrice;
                    r["SubsidyRate"] = item.SubsidyRate;
                    r["SubsidyPrice"] = item.SubsidyPrice;
                    r["OrderID"] = item.OrderID;
                    r["ClassName"] = item.ClassName;
                    r["SourceMediaName"] = item.SourceMediaName;
                    r["AdvID"] = item.AdvID;
                    r["AdvName"] = item.AdvName;
       
                    r["AlimamaID"] = item.AlimamaID;
                    r["Au_Name"] = item.Au_Name;
                    r["BatchNumber"] = item.BatchNumber;
                    dt.Rows.Add(r);

                }
                OrdersDAL.BulkToDB(dt, TableName);
                Log += "新增了：" + values.Count + "条....";
            }
            Result result = new Result();
            return ResultHand.OnResult(new Result { State = true, Message = "查询成功", Datas = Log });
        }


        

        /// <summary>
        /// 批量拉取订单
        /// </summary>
        /// <param name="values"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/updateOrder")]
        public HttpResponseMessage updateOrder(List<OrderDTO> values, string StartTime, string EndTime, int IsDelete, string promoter_id,string QueryType)
        {
            string Log = "";
            if (values != null && values.Count > 0)
            {
                //删除
                if (IsDelete == 1 && !string.IsNullOrEmpty(StartTime) && !string.IsNullOrEmpty(EndTime))
                {
                    string DelStr = "";
                    if (QueryType == "3")
                    {
                        foreach (var item in values)
                        {
                            DelStr += string.Format(" DELETE FROM Orders_{0} WHERE  datediff(day,CreateDate,'{1}')=0 ADN OrderID='{2}' AND BatchNumber!='{3}'; ", promoter_id, item.CreateDate, item.OrderID,item.BatchNumber);
                        }
                       
                    }
                    else {
                        DelStr = string.Format("DELETE FROM Orders_{0} WHERE  CreateDate>='{1}' AND CreateDate<'{2}'; ", promoter_id, StartTime, EndTime);
                    }
                    int delCount = OrdersDAL.BulkDelte(DelStr);
                    Log += "删除了：" + delCount + "条....";
                }
                string TableName =string.Format("Orders_{0}",promoter_id);
                DataTable dt = GetTableSchema();
                foreach (var item in values)
                {
                    DataRow r = dt.NewRow();
                    r["Id"] = 0;
                    r["CreateDate"] = Convert.ToDateTime(item.CreateDate);
                    r["ClickDate"] = Convert.ToDateTime(item.ClickDate);
                    r["ProductDes"] = item.ProductDes;
                    r["ProductID"] = item.ProductID;
                    r["ShopName"] = item.ShopName;
                    r["ProductNum"] = item.ProductNum;
                    r["ProductPrice"] = item.ProductPrice;
                    r["OrderStateDes"] = item.OrderStateDes;
                    r["OrderType"] = item.OrderType;
                    r["IncomeRatio"] = item.IncomeRatio;
                    r["DividedIntoRatio"] = item.DividedIntoRatio;
                    r["PayPrice"] = item.PayPrice;
                    r["EffectPrediction"] = item.EffectPrediction;
                    r["SettlementPrice"] = item.SettlementPrice;
                    r["EstimatedRevenue"] = item.EstimatedRevenue;
                    object obj = item.SettlementDate;
                    if (item.SettlementDate == "")
                    {
                        obj = DBNull.Value;
                    }
                    r["SettlementDate"] = obj;
                    r["CommissionRate"] = item.CommissionRate;
                    r["CommissionPrice"] = item.CommissionPrice;
                    r["SubsidyRate"] = item.SubsidyRate;
                    r["SubsidyPrice"] = item.SubsidyPrice;
                    r["OrderID"] = item.OrderID;
                    r["ClassName"] = item.ClassName;
                    r["SourceMediaName"] = item.SourceMediaName;
                    r["AdvID"] = item.AdvID;
                    r["AdvName"] = item.AdvName;
                    r["AlimamaID"] = item.AlimamaID;
                    r["Au_Name"] = item.Au_Name;
                    r["BatchNumber"] = item.BatchNumber;
                    dt.Rows.Add(r);
                }
                OrdersDAL.BulkToDB(dt, TableName);
                Log += "新增了：" + values.Count + "条....";
            }
            Result result = new Result();
            return ResultHand.OnResult(new Result { State = true, Message = "查询成功", Datas = Log });
        }



        private static DataTable GetTableSchema()
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[]
            {  
                        new DataColumn("Id",typeof(int)),  
                        new DataColumn("CreateDate",typeof(DateTime)),  
                        new DataColumn("ClickDate",typeof(DateTime)),  
                        new DataColumn("ProductDes",typeof(string)), 
                        new DataColumn("ProductID",typeof(long)), 
                        new DataColumn("ShopName",typeof(string)), 
                        new DataColumn("ProductNum",typeof(int)), 
                        new DataColumn("ProductPrice",typeof(double)), 
                        new DataColumn("OrderStateDes",typeof(string)), 
                        new DataColumn("OrderType",typeof(string)), 
                        new DataColumn("IncomeRatio",typeof(string)), 
                        new DataColumn("DividedIntoRatio",typeof(string)), 
                        new DataColumn("PayPrice",typeof(double)), 
                        new DataColumn("EffectPrediction",typeof(double)), 
                        new DataColumn("SettlementPrice",typeof(double)), 
                        new DataColumn("EstimatedRevenue",typeof(double)), 
                        new DataColumn("SettlementDate",typeof(DateTime)), 
                        new DataColumn("CommissionRate",typeof(string)), 
                        new DataColumn("CommissionPrice",typeof(double)), 
                        new DataColumn("SubsidyRate",typeof(string)), 
                        new DataColumn("SubsidyPrice",typeof(double)), 
                        new DataColumn("OrderID",typeof(string)), 
                         new DataColumn("ClassName",typeof(string)), 
                        new DataColumn("SourceMediaName",typeof(string)),
                        new DataColumn("AdvID",typeof(string)),
                        new DataColumn("AdvName",typeof(string)),
                        new DataColumn("AlimamaID",typeof(string)),
                        new DataColumn("Au_Name",typeof(string)),
                        new DataColumn("BatchNumber",typeof(string))
               
            });
            return dt;
        }

        /// <summary>
        /// 汇总表格
        /// </summary>
        /// <returns></returns>
        private static DataTable GetTableEffect()
        {
         
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[]
            {  
                        new DataColumn("Id",typeof(int)),  
                        new DataColumn("CreateDate",typeof(DateTime)),  
                        new DataColumn("PromotionBit",typeof(string)),  
                         new DataColumn("ClickNum",typeof(int)), 
                        new DataColumn("PayNum",typeof(int)), 
                        new DataColumn("Estimate",typeof(double)), 
                        new DataColumn("Income",typeof(double)), 
                        new DataColumn("PromotionType",typeof(int)), 
                        new DataColumn("LastDate",typeof(DateTime)), 
                       // new DataColumn("promoter_id",typeof(int)), 
                        new DataColumn("AlimamaID",typeof(string)), 
                        new DataColumn("UserName",typeof(string)), 
                        new DataColumn("Rate",typeof(int)), 
                        new DataColumn("Rate_i",typeof(int)), 
                        new DataColumn("UserName_i",typeof(string)), 
                        new DataColumn("Rate_ii",typeof(int)), 
                        new DataColumn("UserName_ii",typeof(string))
            });
            return dt;

        }
	}
}